import { bookmarkManager } from '../manager.js';
import storage from './storage.js';
import { showNotification } from './notification.js';
import { get as i18nGet } from './i18n.js';

const browser = chrome;
const AUTO_SYNC_KEY = 'auto_sync_config';

class SyncTimer {
  constructor() {
    this.config = null;
    this.init();
  }

  async init() {
    await this.loadConfig();
    this.setupAlarm();
  }

  async loadConfig() {
    const config = await storage.getItem(AUTO_SYNC_KEY);
    this.config = config ? JSON.parse(config) : null;
  }

  async saveConfig(config) {
    this.config = config;
    await storage.setItem(AUTO_SYNC_KEY, JSON.stringify(config));
    this.setupAlarm();

    if (config.enabled) {
      showNotification(i18nGet('AUTO_SYNC_STARTED'));
    } else {
      showNotification(i18nGet('AUTO_SYNC_STOPPED'));
    }
  }

  setupAlarm() {
    // 清除现有闹钟
    browser.alarms.clear('auto_sync');

    if (!this.config || !this.config.enabled) {
      return;
    }

    // 设置新闹钟
    let alarmInfo = {};

    switch (this.config.frequency) {
      case 'daily':
        alarmInfo = { when: Date.now() + 86400000, periodInMinutes: 1440 };
        break;
      case 'weekly':
        alarmInfo = { when: Date.now() + 604800000, periodInMinutes: 10080 };
        break;
      case 'custom':
        const minutes = parseInt(this.config.interval, 10) || 60;
        alarmInfo = { when: Date.now() + (minutes * 60000), periodInMinutes: minutes };
        break;
      default:
        return;
    }

    browser.alarms.create('auto_sync', alarmInfo);
  }

  async performSync() {
    try {
      await bookmarkManager.syncFromRemote();
    } catch (error) {
      console.error('自动同步失败:', error);
    }
  }
}

// 注册闹钟监听
browser.alarms.onAlarm.addListener((alarm) => {
  if (alarm.name === 'auto_sync') {
    const syncTimer = new SyncTimer();
    syncTimer.performSync();
  }
});

export const syncTimer = new SyncTimer();